package com.xz.freshmall.taomi.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.manor.common.CommonAppConfig;
import com.manor.common.Constants;
import com.manor.common.activity.BaseLocationActivity;
import com.manor.common.bean.ConfigBean;
import com.manor.common.bean.UserBean;
import com.manor.common.em.AuthType;
import com.manor.common.event.AuthResultEvent;
import com.manor.common.event.LoginSuccessEvent;
import com.manor.common.http.CommonHttpConsts;
import com.manor.common.http.CommonHttpUtil;
import com.manor.common.http.HttpCallback;
import com.manor.common.http.JHttpCallback;
import com.manor.common.interfaces.CommonCallback;
import com.manor.common.utils.ActivityManager;
import com.manor.common.utils.GsonUtil;
import com.manor.common.utils.KLog;
import com.manor.common.utils.RouteUtil;
import com.manor.common.utils.SpUtil;
import com.manor.common.utils.StringUtil;
import com.manor.common.utils.ToastUtil;
import com.manor.main.activity.LoginGenderAgeActivity;
import com.manor.main.activity.MainActivity;
import com.manor.main.bean.LoginBean;
import com.manor.main.http.JMainHttpUtil;
import com.manor.main.http.MainHttpConsts;
import com.manor.main.http.MainHttpUtil;
import com.manor.main.login.VCodeVerifyFragment;
import com.xz.freshmall.R;
import com.mob.adsdk.AdSdk;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

/**
 * Created by cxf on 2018/9/17.
 */
@Route(path = RouteUtil.PATH_LAUNCHER)
public class LauncherActivity extends BaseLocationActivity {

    private final int MY_READ_PHONE_STATE = 0;
    public static final int REQUEST_CODE_SETTING = 11;
    private boolean mFirstLogin;//是否是第一次登录

    @Override
    protected int getLayoutId() {
        return R.layout.activity_launcher;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        if (!isTaskRoot()
                && intent != null
                && intent.hasCategory(Intent.CATEGORY_LAUNCHER)
                && intent.getAction() != null
                && intent.getAction().equals(Intent.ACTION_MAIN)) {
            finish();
            return;
        }
        setStatusBar();
        setPermission();
//        initAdvert();//上线
//        EventBus.getDefault().register(this);
        getConfig();
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        MainHttpUtil.cancel(MainHttpConsts.GET_BASE_INFO);
        CommonHttpUtil.cancel(CommonHttpConsts.GET_CONFIG);
        super.onDestroy();
    }


    private final int SPLASH_LOAD_TIMEOUT = 5000;

    private void initAdvert() {
        FrameLayout container = findViewById(R.id.splash_container);
        AdSdk.getInstance().loadSplashAd(LauncherActivity.this, "s1", container, SPLASH_LOAD_TIMEOUT,
                new AdSdk.SplashAdListener() {
                    @Override
                    public void onAdLoad(String s) {

                    }

                    @Override
                    public void onAdShow(String id) {
                    }

                    @Override
                    public void onAdClick(String id) {
                    }

                    @Override
                    public void onAdDismiss(String id) {
                        KLog.e("Launcher#AdSdk", "onAdDismiss");
                        if (!isFinishing()) {
                            setPermission();
                        }
                    }

                    @Override
                    public void onError(String id, int code, String message) {
                        KLog.e("Launcher#AdSdk", "code = " + code + " , message = " + message);
                        setPermission();
                    }
                });
    }


    private void setPermission() {
        PermissionUtils.permission(

        ).callback(new PermissionUtils.FullCallback() {
            @Override
            public void onGranted(@NonNull List<String> granted) {
                getLocation();
                getCheckPermissions();
            }

            @Override
            public void onDenied(@NonNull List<String> deniedForever, @NonNull List<String> denied) {

            }
        });
        AndPermission.with(this)
                .runtime()
                .permission(
                        Permission.READ_EXTERNAL_STORAGE,
                        Permission.WRITE_EXTERNAL_STORAGE,
                        Permission.READ_PHONE_STATE,
                        Permission.ACCESS_COARSE_LOCATION,
                        Permission.ACCESS_FINE_LOCATION)
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> data) {
                        if (!lacksPermission(LauncherActivity.this, Permission.ACCESS_COARSE_LOCATION)
                                && !lacksPermission(LauncherActivity.this, Permission.WRITE_EXTERNAL_STORAGE)
                                && !lacksPermission(LauncherActivity.this, Permission.READ_PHONE_STATE)
                        ) {
                            getLocation();
                            getCheckPermissions();
                        }
                    }
                })
                .onDenied(data -> {
                    for (int i = 0; i < data.size(); i++) {
                        KLog.e("tag", data.get(i) + "");
                        if (lacksPermission(LauncherActivity.this, Permission.ACCESS_COARSE_LOCATION)) {
                            Toast.makeText(LauncherActivity.this,
                                    getResources().getString(R.string.permissions_location), Toast.LENGTH_SHORT).show();
                            if (AndPermission.hasAlwaysDeniedPermission(LauncherActivity.this, data)) {
                                showSettingDialog(LauncherActivity.this,
                                        getResources().getString(R.string.permissions_location),
                                        REQUEST_CODE_SETTING);
                            } else {
                                setPermission();
                            }
                            return;
                        }
                        if (lacksPermission(LauncherActivity.this, Permission.WRITE_EXTERNAL_STORAGE)) {
                            Toast.makeText(LauncherActivity.this,
                                    getResources().getString(R.string.permissions_storage), Toast.LENGTH_SHORT).show();
                            if (AndPermission.hasAlwaysDeniedPermission(LauncherActivity.this, data)) {
                                showSettingDialog(LauncherActivity.this,
                                        getResources().getString(R.string.permissions_storage),
                                        REQUEST_CODE_SETTING);
                            } else {
                                setPermission();
                            }
                            return;
                        }
                        if (lacksPermission(LauncherActivity.this, Permission.READ_PHONE_STATE)) {
                            Toast.makeText(LauncherActivity.this,
                                    getResources().getString(R.string.permissions_equipment), Toast.LENGTH_SHORT).show();
                            if (AndPermission.hasAlwaysDeniedPermission(LauncherActivity.this, data)) {
                                showSettingDialog(LauncherActivity.this,
                                        getResources().getString(R.string.permissions_equipment),
                                        REQUEST_CODE_SETTING);
                            } else {
                                setPermission();
                            }
                            return;
                        }
                    }
                }).start();
    }


    private void getCheckPermissions() {
        if (isLocServiceEnable(this)) {
            checkUidAndToken();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_SETTING:
                setPermission();
                break;
            case 10:
                getLocation();
                getCheckPermissions();
                break;
        }
    }

    private void requestPermission(String permission) {
        if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
            if ("OPPO".equals(Build.MANUFACTURER)) {
                //OPPO机型动态申请权限前建议弹出一个提示框，可提高成功率
                startRunnable(permission);
            } else {
                ActivityCompat.requestPermissions(LauncherActivity.this, new String[]{permission}, MY_READ_PHONE_STATE);
            }
        }
    }

    private void onLoginSuccess(int code, String msg, String info) {

        if (code == 200 && !info.equals("")) {
            LoginBean loginBean = GsonUtil.gsonToBean(info, LoginBean.class);
            parentSdNo = loginBean.getParentSdNo();
            SpUtil.getInstance().setStringValue(SpUtil.TX_IM_USER_SIGN, loginBean.getUsersig());
            KLog.e("tag", loginBean.getUsersig());
            //友盟统计登录
            MobclickAgent.onProfileSignIn(Constants.MOB_PHONE, loginBean.getUid());
            EventBus.getDefault().post(new LoginSuccessEvent());
            SpUtil.getInstance().setStringValue(SpUtil.JAVA_TOKEN,
                    loginBean.getTokenType() + " " + loginBean.getAccessToken());
            //通知服务器ios Android设备切换
            //losToken(loginBean.getUid(), loginBean.getAccessToken());
            CommonAppConfig.getInstance().setLoginInfo(loginBean.getUid(), loginBean.getAccessToken(), true);
            isFirstRegister(loginBean.getNikeName());//判断是不是已注册用户
        } else {
            ToastUtil.show(msg);
        }
    }
//
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onFaceResult(AuthResultEvent e) {
//        if (e.getCode() == 200) {
//            reLogin(my_token, "1");
//        } else {
//            ToastUtil.show(e.getMsg());
//        }
//    }

    private void isFirstRegister(String name) {
        if (name.equals("")) {
            //进入填写资料页面
            LoginGenderAgeActivity.forward(0);
            finish();
        } else {
            getBaseUserInfo();
        }
    }


    /**
     * 获取用户信息
     */
    private void getBaseUserInfo() {
        MainHttpUtil.getBaseInfo(new CommonCallback<UserBean>() {
            @Override
            public void callback(UserBean bean) {
                MainActivity.Companion.forward(LauncherActivity.this, mFirstLogin);
                finish();
            }
        });
    }


    /**
     * 获取Config信息
     */
    private void getConfig() {
        CommonHttpUtil.getConfig(new CommonCallback<ConfigBean>() {
            @Override
            public void callback(ConfigBean bean) {
                if (bean != null) {
                } else {
                    //ToastUtil.show("获取信息错误，请稍后重试");
                    ActivityManager.getInstance().exit(LauncherActivity.this);
                }
            }
        });
    }

    /**
     * 检查uid和token是否存在
     */
    private void checkUidAndToken() {

        if (DeviceUtils.isEmulator()) {
            new XPopup.Builder(this)
                    .dismissOnBackPressed(false)
                    .dismissOnTouchOutside(false)
                    .asConfirm("提示", "APP暂不支持模拟器用户，请使用手机登录", new OnConfirmListener() {
                        @Override
                        public void onConfirm() {
                            AppUtils.exitApp();
                        }
                    }, () -> AppUtils.exitApp())
                    .show();
            return;
        }


        String[] uidAndToken = SpUtil.getInstance().getMultiStringValue(SpUtil.UID, SpUtil.TOKEN);
        final String uid = uidAndToken[0];
        final String token = uidAndToken[1];
        if (!TextUtils.isEmpty(uid) && !TextUtils.isEmpty(token)) {

            if (!AndPermission.hasPermissions(LauncherActivity.this, Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.ACCESS_WIFI_STATE)) {
                CommonHttpUtil.ifToken(uid, token, tokenCallBack);
            } else {
                CommonHttpUtil.ifTokenL(uid, token, tokenCallBack);
            }
        } else {
            // requestPermission(Manifest.permission.READ_PHONE_STATE);
            ARouter.getInstance()
                    .build(RouteUtil.PATH_LOGIN)
                    .withInt(VCodeVerifyFragment.FLAG_FROM_TYPE,4)
                    .navigation();
            finish();
        }
    }

    private final HttpCallback tokenCallBack = new HttpCallback() {
        @Override
        public void onSuccess(int code, String msg, String info) {
            if (code == 0) {
                String[] uidAndToken = SpUtil.getInstance().getMultiStringValue(SpUtil.UID, SpUtil.TOKEN);
                final String uid = uidAndToken[0];
                final String token = uidAndToken[1];
                CommonAppConfig.getInstance().setLoginInfo(uid, token, false);
                forwardMainActivity();
            } else {
                requestPermission(Manifest.permission.READ_PHONE_STATE);
            }
        }

        @Override
        public void onError() {
            super.onError();
            requestPermission(Manifest.permission.READ_PHONE_STATE);
        }
    };
    /**
     * 跳转到首页
     */
    private void forwardMainActivity() {
        MainActivity.Companion.forward(this);
        finish();
    }

    /**
     * 设置透明状态栏
     */
    private void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(0);
        }
    }

    private void startRunnable(final String permission) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("将会有一些权限需要被授予");
        builder.setPositiveButton("确定", (dialog, which) -> ActivityCompat.requestPermissions(LauncherActivity.this, new String[]{permission}, MY_READ_PHONE_STATE));
        builder.setCancelable(false);//弹出框不可以返回键取消
        AlertDialog dialog = builder.create();
        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);//将弹出框设置为全局
        dialog.setCanceledOnTouchOutside(false);//失去焦点不会消失
        builder.show();
    }

    public static void forward(Context context) {
        context.startActivity(new Intent(context, LauncherActivity.class));
    }
}
